<template>
  <div class="documents-container">
    <div class="header">
      <h2>文档管理</h2>
      <el-upload
        class="upload-btn"
        :auto-upload="true"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        accept=".txt,.md,.markdown,.doc,.docx,.pdf"
        action="/api/documents/upload"
      >
        <el-button type="primary">
          <el-icon><Upload /></el-icon>
          上传文档
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持 txt、markdown、word、pdf 格式文件
          </div>
        </template>
      </el-upload>
    </div>

    <el-table
      v-loading="loading"
      :data="documents"
      style="width: 100%"
      border
    >
      <el-table-column prop="title" label="文档名称" min-width="200">
        <template #default="{ row }">
          <div class="document-title" @click="previewDocument(row)">
            <el-icon><Document /></el-icon>
            <span>{{ row.title }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag size="small">{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="size" label="大小" width="120">
        <template #default="{ row }">
          {{ formatSize(row.size) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 'vectorized' ? 'success' : 'warning'">
            {{ row.status === 'vectorized' ? '已向量化' : '待处理' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="uploadTime" label="上传时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.uploadTime) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <div class="action-buttons">
            <!-- 预览按钮 -->
            <el-tooltip content="预览文档" placement="top">
              <el-button
                type="primary"
                :icon="Document"
                circle
                plain
                @click="previewDocument(row)"
              />
            </el-tooltip>

            <!-- 向量化按钮 -->
            <el-tooltip 
              :content="vectorizing === row.id ? '处理中...' : '向量化文档'" 
              placement="top"
            >
              <el-button
                v-if="row.status !== 'vectorized'"
                type="success"
                :icon="Upload"
                circle
                plain
                :loading="vectorizing === row.id"
                @click="handlePreviewChunks(row)"
              />
            </el-tooltip>

            <!-- 查看向量化内容按钮 -->
            <el-tooltip content="查看向量化内容" placement="top">
              <el-button
                v-if="row.status === 'vectorized'"
                type="info"
                :icon="Connection"
                circle
                plain
                @click="handleViewVectorized(row)"
              />
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip content="删除文档" placement="top">
              <el-button
                type="danger"
                :icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
              />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <document-preview
      v-model="previewVisible"
      :document="currentDocument"
      @vectorized="handleVectorized"
    />

    <vectorized-content-dialog
      v-model:visible="showVectorizedContent"
      :document="selectedDocument"
      @deleted="handleVectorizedContentDeleted"
    />

    <chunk-preview-dialog
      v-model="showChunkPreview"
      :document="currentDocument"
      @confirm="handleChunkPreviewConfirm"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Document, Upload, Delete, Connection } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDocumentsStore } from '@/store/documents'
import { formatTime } from '@/utils/time'
import { formatSize } from '@/utils/file'
import DocumentPreview from '@/components/documents/DocumentPreview.vue'
import VectorizedContentDialog from '@/components/documents/VectorizedContentDialog.vue'
import ChunkPreviewDialog from '@/components/documents/ChunkPreviewDialog.vue'
import { 
  getDocuments, 
  uploadDocument, 
  deleteDocument, 
  getDocumentContent,
  vectorizeDocument
} from '@/api/documents'

const documentsStore = useDocumentsStore()
const documents = ref([])
const loading = ref(false)
const vectorizing = ref(null)
const previewVisible = ref(false)
const showVectorizedContent = ref(false)
const selectedDocument = ref(null)
const currentDocument = ref(null)
const showChunkPreview = ref(false)

// 获取文档列表
const fetchDocuments = async () => {
  loading.value = true
  try {
    const response = await getDocuments()
    documents.value = response.data.list || []
  } catch (error) {
    console.error('获取文档列表失败:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 处理文件上传前的验证
const handleBeforeUpload = (file) => {
  // 检查文件类型
  const allowedTypes = [
    'text/plain',
    'text/markdown',
    'text/x-markdown',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  
  // 检查文件扩展名
  const allowedExtensions = ['.txt', '.md', '.markdown', '.doc', '.docx', '.pdf']
  const extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
  
  if (!allowedTypes.includes(file.type) && !allowedExtensions.includes(extension)) {
    ElMessage.error('只能上传 TXT、Markdown、Word、PDF 格式的文件!')
    return false
  }
  
  // 检查文件大小（150MB）
  const isLt150M = file.size / 1024 / 1024 < 150
  if (!isLt150M) {
    ElMessage.error('文件大小不能超过 150MB!')
    return false
  }
  
  return true
}

// 上传成功
const handleUploadSuccess = (response) => {
  ElMessage.success('文档上传成功')
  fetchDocuments()
}

// 上传失败
const handleUploadError = (error) => {
  console.error('Upload error:', error)
  ElMessage.error(error?.message || '文档上传失败')
}

// 预览文档
const previewDocument = (document) => {
  currentDocument.value = document
  previewVisible.value = true
}

// 删除文档
const handleDelete = async (document) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该文档吗？删除后无法恢复。',
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    await deleteDocument(document.id)
    ElMessage.success('文档删除成功')
    await fetchDocuments()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error)
      ElMessage.error('文档删除失败')
    }
  }
}

// 向量化处理
const handleVectorize = async (document, config = {}) => {
  vectorizing.value = document.id
  try {
    ElMessage({
      type: 'info',
      message: '开始向量化处理，这可能需要几分钟时间...',
      duration: 0,
      showClose: true,
      customClass: 'vectorize-message'
    })

    await vectorizeDocument(document.id, (data) => {
      // 处理进度更新
      if (data.status === 'processing') {
        ElMessage.closeAll()
        ElMessage({
          type: 'info',
          message: `${data.message || '处理中...'} (${data.progress || 0}%)`,
          duration: 0,
          showClose: true,
          customClass: 'vectorize-message'
        })
      }
    })

    ElMessage.closeAll()
    ElMessage.success('向量化处理成功')
    await fetchDocuments()  // 刷新文档列表
  } catch (error) {
    ElMessage.closeAll()
    ElMessage.error(error.message || '向量化处理失败')
    console.error('向量化处理失败:', error)
  } finally {
    vectorizing.value = null
  }
}

// 处理向量化完成事件
const handleVectorized = async (documentId) => {
  await fetchDocuments()
  const updatedDoc = documents.value.find(d => d.id === documentId)
  if (updatedDoc) {
    currentDocument.value = updatedDoc
  }
}

// 查看向量化内容
const handleViewVectorized = (doc) => {
  selectedDocument.value = doc
  showVectorizedContent.value = true
  console.log('Opening dialog for document:', doc)
}

// 处理向量化内容删除
const handleVectorizedContentDeleted = async (documentId) => {
  await fetchDocuments() // 刷新文档列表
  const updatedDoc = documents.value.find(d => d.id === documentId)
  if (updatedDoc) {
    selectedDocument.value = updatedDoc
  }
  ElMessage.success('向量化内容已删除')
}

function handlePreviewChunks(doc) {
  currentDocument.value = doc
  showChunkPreview.value = true
}

async function handleChunkPreviewConfirm(config) {
  // 使用确认的配置开始向量化
  await handleVectorize(currentDocument.value, config)
}

onMounted(() => {
  fetchDocuments()
})
</script>

<style lang="scss" scoped>
.documents-container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
  }
  
  .file-name {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .el-icon {
      font-size: 18px;
      color: var(--el-text-color-secondary);
    }
  }

  .upload-btn {
    margin-left: auto;
  }

  .documents-list {
    .document-title {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      color: var(--el-color-primary);
      
      &:hover {
        text-decoration: underline;
      }
    }
  }

  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 4px;
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    
    .el-button {
      --el-button-size: 32px;
      padding: 6px;
      
      &:hover {
        transform: scale(1.05);
        transition: transform 0.2s ease;
      }
      
      &.is-loading {
        .el-icon {
          animation: rotating 1s linear infinite;
        }
      }
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 